import React, { useState, useEffect, useCallback, useMemo } from 'react'
import {
  Tree,
  Input,
  Button,
  Dropdown,
  Modal,
  Form,
  message,
  Tooltip,
  Space,
  Typography,
  Spin,
  Empty,
} from 'antd'
import {
  FolderOutlined,
  FolderOpenOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  MoreOutlined,
  SearchOutlined,
  ReloadOutlined,
  FolderAddOutlined,
  CopyOutlined,
  ScissorOutlined,
  FileOutlined,
} from '@ant-design/icons'
import type { TreeDataNode, TreeProps } from 'antd'
import { useDrag, useDrop, DndProvider } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import { Folder } from '@/types/folder'
import {
  getFolderTree,
  createFolder,
  updateFolder,
  deleteFolder,
  moveFolder,
  renameFolder,
  getFolderContents,
} from '@/services/folderAPI'

const { Search } = Input
const { Text } = Typography
const { confirm } = Modal

interface FolderTreeProps {
  onFolderSelect?: (folderId: string | null, folder: Folder | null) => void
  selectedFolderId?: string | null
  showSearch?: boolean
  allowEdit?: boolean
  allowDrag?: boolean
  height?: number
  showRoot?: boolean
  rootTitle?: string
}

interface TreeNodeData extends TreeDataNode {
  key: string
  title: React.ReactNode
  children?: TreeNodeData[]
  folder?: Folder
  isLeaf?: boolean
  selectable?: boolean
}

interface DragItem {
  type: string
  id: string
  folder: Folder
}

const FOLDER_TYPE = 'FOLDER_ITEM'

// 可拖拽的树节点组件
const DraggableTreeNode: React.FC<{
  folder: Folder
  children: React.ReactNode
  allowDrag: boolean
  onMove: (dragFolder: Folder, targetFolder: Folder | null) => void
}> = ({ folder, children, allowDrag, onMove }) => {
  const [{ isDragging }, drag] = useDrag({
    type: FOLDER_TYPE,
    item: { type: FOLDER_TYPE, id: folder.id, folder },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
    canDrag: allowDrag,
  })

  const [{ isOver, canDrop }, drop] = useDrop({
    accept: FOLDER_TYPE,
    drop: (item: DragItem) => {
      if (item.id !== folder.id) {
        onMove(item.folder, folder)
      }
    },
    collect: (monitor) => ({
      isOver: monitor.isOver(),
      canDrop: monitor.canDrop(),
    }),
  })

  const ref = useCallback((node: HTMLDivElement) => {
    if (allowDrag) {
      drag(drop(node))
    }
  }, [drag, drop, allowDrag])

  return (
    <div
      ref={ref}
      style={{
        opacity: isDragging ? 0.5 : 1,
        backgroundColor: isOver && canDrop ? '#e6f7ff' : 'transparent',
        cursor: allowDrag ? 'move' : 'default',
      }}
    >
      {children}
    </div>
  )
}

const FolderTree: React.FC<FolderTreeProps> = ({
  onFolderSelect,
  selectedFolderId,
  showSearch = true,
  allowEdit = true,
  allowDrag = true,
  height = 400,
  showRoot = true,
  rootTitle = '所有脚本',
}) => {
  const [folders, setFolders] = useState<Folder[]>([])
  const [loading, setLoading] = useState(false)
  const [searchKeyword, setSearchKeyword] = useState('')
  const [expandedKeys, setExpandedKeys] = useState<string[]>([])
  const [selectedKeys, setSelectedKeys] = useState<string[]>([])
  const [autoExpandParent, setAutoExpandParent] = useState(true)

  // 模态框状态
  const [createModalVisible, setCreateModalVisible] = useState(false)
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [currentFolder, setCurrentFolder] = useState<Folder | null>(null)
  const [parentFolder, setParentFolder] = useState<Folder | null>(null)

  const [createForm] = Form.useForm()
  const [editForm] = Form.useForm()

  // 加载文件夹树
  const loadFolderTree = useCallback(async () => {
    setLoading(true)
    try {
      const response = await getFolderTree()
      if (response.success) {
        setFolders(response.data || [])
      }
    } catch (error) {
      console.error('加载文件夹树失败:', error)
      message.error('加载文件夹树失败')
    } finally {
      setLoading(false)
    }
  }, [])

  // 构建树形数据
  const buildTreeData = useCallback((folders: Folder[], searchKeyword?: string): TreeNodeData[] => {
    const folderMap = new Map<string, Folder>()
    const rootFolders: Folder[] = []

    // 构建文件夹映射和根文件夹列表
    folders.forEach(folder => {
      folderMap.set(folder.id, folder)
      if (!folder.parent_id) {
        rootFolders.push(folder)
      }
    })

    // 递归构建子文件夹
    const buildChildren = (parentId: string): TreeNodeData[] => {
      return folders
        .filter(folder => folder.parent_id === parentId)
        .map(folder => ({
          key: folder.id,
          title: renderTreeNodeTitle(folder),
          folder,
          children: buildChildren(folder.id),
          selectable: true,
        }))
    }

    // 构建树形结构
    const treeData: TreeNodeData[] = rootFolders.map(folder => ({
      key: folder.id,
      title: renderTreeNodeTitle(folder),
      folder,
      children: buildChildren(folder.id),
      selectable: true,
    }))

    // 如果有搜索关键词，过滤节点
    if (searchKeyword) {
      return filterTreeData(treeData, searchKeyword)
    }

    return treeData
  }, [allowEdit, allowDrag])

  // 渲染树节点标题
  const renderTreeNodeTitle = (folder: Folder) => {
    const contextMenuItems = allowEdit ? [
      {
        key: 'create',
        icon: <FolderAddOutlined />,
        label: '新建子文件夹',
        onClick: () => handleCreateFolder(folder),
      },
      {
        key: 'rename',
        icon: <EditOutlined />,
        label: '重命名',
        onClick: () => handleRenameFolder(folder),
      },
      {
        key: 'copy',
        icon: <CopyOutlined />,
        label: '复制',
        onClick: () => handleCopyFolder(folder),
      },
      {
        type: 'divider' as const,
      },
      {
        key: 'delete',
        icon: <DeleteOutlined />,
        label: '删除',
        danger: true,
        onClick: () => handleDeleteFolder(folder),
      },
    ] : []

    return (
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          width: '100%',
          padding: '2px 4px',
        }}
        onContextMenu={(e) => e.preventDefault()}
      >
        <Space size={4}>
          <FolderOutlined style={{ color: '#1890ff' }} />
          <Text ellipsis style={{ maxWidth: 150 }}>
            {folder.name}
          </Text>
        </Space>
        
        {allowEdit && (
          <Dropdown
            menu={{ items: contextMenuItems }}
            trigger={['click']}
            placement="bottomRight"
            onClick={(e) => e.stopPropagation()}
          >
            <Button
              type="text"
              size="small"
              icon={<MoreOutlined />}
              style={{ opacity: 0.6 }}
              onClick={(e) => e.stopPropagation()}
            />
          </Dropdown>
        )}
      </div>
    )
  }

  // 过滤树形数据
  const filterTreeData = (treeData: TreeNodeData[], keyword: string): TreeNodeData[] => {
    const filterNode = (node: TreeNodeData): TreeNodeData | null => {
      const folder = node.folder
      if (!folder) return null

      const matchesKeyword = folder.name.toLowerCase().includes(keyword.toLowerCase())
      const filteredChildren = node.children?.map(filterNode).filter(Boolean) as TreeNodeData[] || []

      if (matchesKeyword || filteredChildren.length > 0) {
        return {
          ...node,
          children: filteredChildren,
        }
      }

      return null
    }

    return treeData.map(filterNode).filter(Boolean) as TreeNodeData[]
  }

  // 处理文件夹选择
  const handleFolderSelect = (selectedKeys: React.Key[], info: any) => {
    const folderId = selectedKeys[0] as string
    const folder = info.node?.folder || null
    
    setSelectedKeys(selectedKeys as string[])
    onFolderSelect?.(folderId || null, folder)
  }

  // 处理展开/收起
  const handleExpand = (expandedKeys: React.Key[]) => {
    setExpandedKeys(expandedKeys as string[])
    setAutoExpandParent(false)
  }

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchKeyword(value)
    if (value) {
      // 展开所有匹配的节点
      const expandedKeys = folders
        .filter(folder => folder.name.toLowerCase().includes(value.toLowerCase()))
        .map(folder => folder.id)
      setExpandedKeys(expandedKeys)
      setAutoExpandParent(true)
    }
  }

  // 处理创建文件夹
  const handleCreateFolder = (parentFolder?: Folder) => {
    setParentFolder(parentFolder || null)
    setCreateModalVisible(true)
    createForm.resetFields()
  }

  // 处理重命名文件夹
  const handleRenameFolder = (folder: Folder) => {
    setCurrentFolder(folder)
    setEditModalVisible(true)
    editForm.setFieldsValue({ name: folder.name })
  }

  // 处理复制文件夹
  const handleCopyFolder = (folder: Folder) => {
    // TODO: 实现复制逻辑
    message.info('复制功能开发中...')
  }

  // 处理删除文件夹
  const handleDeleteFolder = (folder: Folder) => {
    confirm({
      title: '确认删除',
      content: `确定要删除文件夹 "${folder.name}" 吗？此操作将同时删除文件夹内的所有脚本和子文件夹。`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await deleteFolder(folder.id, true)
          if (response.success) {
            message.success('文件夹删除成功')
            loadFolderTree()
            // 如果删除的是当前选中的文件夹，清除选择
            if (selectedFolderId === folder.id) {
              onFolderSelect?.(null, null)
            }
          }
        } catch (error) {
          console.error('删除文件夹失败:', error)
          message.error('删除文件夹失败')
        }
      },
    })
  }

  // 处理文件夹移动
  const handleFolderMove = async (dragFolder: Folder, targetFolder: Folder | null) => {
    try {
      const response = await moveFolder(dragFolder.id, targetFolder?.id)
      if (response.success) {
        message.success('文件夹移动成功')
        loadFolderTree()
      }
    } catch (error) {
      console.error('移动文件夹失败:', error)
      message.error('移动文件夹失败')
    }
  }

  // 提交创建文件夹
  const handleCreateSubmit = async (values: { name: string }) => {
    try {
      const response = await createFolder({
        name: values.name,
        parent_id: parentFolder?.id,
      })
      
      if (response.success) {
        message.success('文件夹创建成功')
        setCreateModalVisible(false)
        loadFolderTree()
        
        // 展开父文件夹
        if (parentFolder) {
          setExpandedKeys(prev => [...prev, parentFolder.id])
        }
      }
    } catch (error) {
      console.error('创建文件夹失败:', error)
      message.error('创建文件夹失败')
    }
  }

  // 提交重命名文件夹
  const handleRenameSubmit = async (values: { name: string }) => {
    if (!currentFolder) return

    try {
      const response = await renameFolder(currentFolder.id, values.name)
      if (response.success) {
        message.success('文件夹重命名成功')
        setEditModalVisible(false)
        loadFolderTree()
      }
    } catch (error) {
      console.error('重命名文件夹失败:', error)
      message.error('重命名文件夹失败')
    }
  }

  // 处理根节点选择
  const handleRootSelect = () => {
    setSelectedKeys([])
    onFolderSelect?.(null, null)
  }

  // 构建完整的树形数据（包含根节点）
  const fullTreeData = useMemo(() => {
    const folderTreeData = buildTreeData(folders, searchKeyword)
    
    if (showRoot) {
      return [
        {
          key: 'root',
          title: (
            <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
              <FileOutlined style={{ color: '#1890ff' }} />
              <Text strong>{rootTitle}</Text>
            </div>
          ),
          children: folderTreeData,
          selectable: true,
        },
      ]
    }
    
    return folderTreeData
  }, [folders, searchKeyword, showRoot, rootTitle, buildTreeData])

  // 初始化加载
  useEffect(() => {
    loadFolderTree()
  }, [loadFolderTree])

  // 同步选中状态
  useEffect(() => {
    if (selectedFolderId) {
      setSelectedKeys([selectedFolderId])
    } else {
      setSelectedKeys(showRoot ? ['root'] : [])
    }
  }, [selectedFolderId, showRoot])

  return (
    <DndProvider backend={HTML5Backend}>
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        {/* 搜索框 */}
        {showSearch && (
          <div style={{ marginBottom: 12 }}>
            <Search
              placeholder="搜索文件夹..."
              allowClear
              onSearch={handleSearch}
              onChange={(e) => !e.target.value && handleSearch('')}
              style={{ width: '100%' }}
            />
          </div>
        )}

        {/* 工具栏 */}
        {allowEdit && (
          <div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
            <Tooltip title="新建文件夹">
              <Button
                size="small"
                icon={<PlusOutlined />}
                onClick={() => handleCreateFolder()}
              >
                新建
              </Button>
            </Tooltip>
            <Tooltip title="刷新">
              <Button
                size="small"
                icon={<ReloadOutlined />}
                onClick={loadFolderTree}
              />
            </Tooltip>
          </div>
        )}

        {/* 文件夹树 */}
        <div style={{ flex: 1, overflow: 'auto' }}>
          <Spin spinning={loading}>
            {fullTreeData.length > 0 ? (
              <Tree
                treeData={fullTreeData}
                selectedKeys={selectedKeys}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                onSelect={handleFolderSelect}
                onExpand={handleExpand}
                showIcon={false}
                blockNode
                height={height}
                virtual
                titleRender={(nodeData) => {
                  const folder = (nodeData as TreeNodeData).folder
                  if (folder && allowDrag) {
                    return (
                      <DraggableTreeNode
                        folder={folder}
                        allowDrag={allowDrag}
                        onMove={handleFolderMove}
                      >
                        {nodeData.title}
                      </DraggableTreeNode>
                    )
                  }
                  return nodeData.title
                }}
              />
            ) : (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description="暂无文件夹"
                style={{ padding: '20px 0' }}
              >
                {allowEdit && (
                  <Button
                    type="primary"
                    size="small"
                    icon={<PlusOutlined />}
                    onClick={() => handleCreateFolder()}
                  >
                    创建第一个文件夹
                  </Button>
                )}
              </Empty>
            )}
          </Spin>
        </div>

        {/* 创建文件夹模态框 */}
        <Modal
          title={`新建文件夹${parentFolder ? ` - ${parentFolder.name}` : ''}`}
          open={createModalVisible}
          onCancel={() => setCreateModalVisible(false)}
          onOk={() => createForm.submit()}
          okText="创建"
          cancelText="取消"
        >
          <Form
            form={createForm}
            layout="vertical"
            onFinish={handleCreateSubmit}
          >
            <Form.Item
              name="name"
              label="文件夹名称"
              rules={[
                { required: true, message: '请输入文件夹名称' },
                { max: 50, message: '文件夹名称不能超过50个字符' },
                { pattern: /^[^/\\:*?"<>|]+$/, message: '文件夹名称不能包含特殊字符' },
              ]}
            >
              <Input placeholder="请输入文件夹名称" autoFocus />
            </Form.Item>
          </Form>
        </Modal>

        {/* 重命名文件夹模态框 */}
        <Modal
          title="重命名文件夹"
          open={editModalVisible}
          onCancel={() => setEditModalVisible(false)}
          onOk={() => editForm.submit()}
          okText="确定"
          cancelText="取消"
        >
          <Form
            form={editForm}
            layout="vertical"
            onFinish={handleRenameSubmit}
          >
            <Form.Item
              name="name"
              label="文件夹名称"
              rules={[
                { required: true, message: '请输入文件夹名称' },
                { max: 50, message: '文件夹名称不能超过50个字符' },
                { pattern: /^[^/\\:*?"<>|]+$/, message: '文件夹名称不能包含特殊字符' },
              ]}
            >
              <Input placeholder="请输入文件夹名称" autoFocus />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </DndProvider>
  )
}

export default FolderTree